import React from 'react';
import { Modal } from 'antd';
import { IMG_TYPE, PDF_TYPE, OFFICE_TYPE } from '../constant';
import { getFileType } from '../utils';

const baseStyle = { border: 0, width: '100%', height: '100%' };

const ModalContent = React.memo(({ fileName, url }) => {
    const fileType = getFileType(fileName);
    if (IMG_TYPE.includes(fileType)) {
        return <img alt={fileName} src={url} style={{ ...baseStyle, objectFit: 'contain' }} />;
    }
    // pdf放入iframe中会直接下载，需要服务端设置header中的content-type
    if (PDF_TYPE.includes(fileType)) {
        return null;
        // return <iframe title={fileName} style={baseStyle} src={url} />;
    }
    if (OFFICE_TYPE.includes(fileType)) {
        const encodeUrl = encodeURIComponent(url);
        const remoteUrl = `https://view.officeapps.live.com/op/view.aspx?src=${encodeUrl}`;
        return <iframe title={fileName} style={baseStyle} src={remoteUrl} />;
    }
    return null;
});

export default React.forwardRef((props, ref) => {
    const [visible, setVisible] = React.useState(false);
    const [file, setFile] = React.useState({});

    const closeModal = () => {
        setVisible(false);
    };

    React.useImperativeHandle(ref, () => ({
        show: (fileName, url) => {
            setFile({ fileName, url });
            setVisible(true);
        }
    }));

    return (
        <Modal
            visible={visible}
            onOk={closeModal}
            onCancel={closeModal}
            width="80vw"
            bodyStyle={{ height: 600 }}
            footer={null}
        >
            <ModalContent fileName={file.fileName} url={file.url} />
        </Modal>
    );
});
